<template>
  <main-card title="AI应用" :tabs="getTabs()" :online-lab="true">
    <template #tool-btn>
      <a-button type="primary" @click="createApp">创建应用</a-button>
    </template>
    <template #screen-space>
      <div class="pb-24">
        <condition-search
          :condition="[
            { name: '名称', key: 'name' },
            { name: '编号', key: 'number' }
          ]"
          @search="onSearch"
        />
      </div>
    </template>
    <a-table
      :style="{ width: '100%' }"
      :columns="tableColumns"
      :data-source="dataList"
      :pagination="false"
      :custom-row="(r:any) => ({ onClick: () => previewDetail(r) })"
      :loading="loading"
      @change="onTableChange"
    >
      <template #bodyCell="{ column, record }">
        <div v-if="column.dataIndex == 'status'" :class="['table__status', record.status === '禁用' && 'error']">
          {{ record.status === '禁用' ? '禁用' : '可用' }}
        </div>
        <template v-else-if="column.dataIndex === 'tools'">
          <a-dropdown placement="bottom" @click.stop>
            <a-button type="text" class="icon-only-btn" @click.stop>
              <i class="iconfont icon-more-line"></i>
            </a-button>
            <template #overlay>
              <a-menu>
                <a-menu-item class="menu-icon-item" @click="goEdit(record.id)"> 编辑 </a-menu-item>
                <a-menu-item class="menu-icon-item" @click="openDeleteModal(record)"> 删除 </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
        <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
      </template>
    </a-table>
    <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getDataList" />
  </main-card>

  <delete-confirm-dialog
    v-model:show="showDeleteModal"
    title="确认删除"
    msg="删除应用将导致所含服务失效，请确认操作"
    label="请输入应用编号"
    :confirm-name="selectApp?.number"
    @ok="deleteApp"
  />
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { ref } from 'vue'
  import { useRouter } from 'vue-router'

  import ConditionSearch, { SearchFn } from '@/components/ConditionInput/index.vue'
  import DeleteConfirmDialog from '@/components/DeleteConfirmDialog/index.vue'
  import useList from '@/hooks/use-list'
  import { appApi } from '@/services/api'
  import { useUserInfoStore } from '@/store'
  import { replaceEmptyStr } from '@/utils'
  import { filterTableColumns } from '@/utils'

  import { getTabs } from '../../utils'

  interface PageForm {
    name: string
    number: string
    columns: 'updateTime' | 'createTime'
    order: 'desc' | 'asc'
  }

  interface Record {
    /**
     * 应用描述
     */
    content: string
    /**
     * 创建时间
     */
    createTime: string
    /**
     * 应用id
     */
    id: string
    /**
     * 应用名称
     */
    name: string
    /**
     * 应用编号
     */
    number: string
    /**
     * 更新时间
     */
    updateTime: string
  }

  // const crumbs: Crumb[] = [
  //   {
  //     name: '应用列表'
  //   }
  // ]

  // 表格
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '编号',
        dataIndex: 'number',
        width: 200
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: 180
      },
      {
        title: '描述',
        dataIndex: 'content'
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        isSort: true,
        width: 190
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        isSort: true,
        width: 190
      },
      {
        title: '',
        dataIndex: 'tools',
        width: 100,
        fixed: 'right'
      }
    ])
  )

  const router = useRouter()
  const { userInfo } = useUserInfoStore()

  const { pageForm, dataList, getDataList, loading } = useList<PageForm, Record>(appApi.list, {
    name: '',
    number: '',
    columns: 'updateTime',
    order: 'desc'
  })

  const onTableChange = (pagination: any, filters: any, sorter: any) => {
    if (!sorter.order) {
      getDataList({ order: 'desc', columns: 'updateTime' })
      return
    }
    const order = sorter.order === 'ascend' ? 'asc' : 'desc'
    getDataList({ offset: 1, order, columns: sorter.field })
  }

  const onSearch: SearchFn = obj => {
    getDataList(obj)
  }

  // 查看详情
  const previewDetail = (item: Record) => {
    router.push(`/ai-app/app-list/detail/${item.id}`)
  }

  /* 删除逻辑 -------------------------------------------------------------------------------- */
  const selectApp = ref<Record>() //当前选中的应用
  const showDeleteModal = ref(false)
  const openDeleteModal = async (item: any) => {
    selectApp.value = item
    showDeleteModal.value = true
  }
  const deleteApp = async () => {
    await appApi.del(selectApp.value!.id)()
    message.success('操作成功')
    showDeleteModal.value = false
    getDataList()
  }

  const goEdit = (id: string) => {
    router.push(`/ai-app/app-list/edit?id=${id}`)
  }

  /*  新增逻辑 -------------------------------------------------------------------------------- */
  const createApp = () => {
    console.log(userInfo, 'userInfos')

    router.push('/ai-app/app-list/add')
  }

  /*   -------------------------------------------------------------------------------- */

  getDataList()
</script>
